package util;

import javax.swing.*;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;

/**
 * 主题管理类，用于管理应用的颜色主题
 */
public class ThemeManager {
    // 主题类型
    public static final String LIGHT_THEME = "light";
    public static final String DARK_THEME = "dark";
    public static final String SYSTEM_THEME = "system";

    // 当前主题
    private static String currentTheme = LIGHT_THEME;

    // 主题颜色映射
    private static final Map<String, Color> lightThemeColors = new HashMap<>();
    private static final Map<String, Color> darkThemeColors = new HashMap<>();

    // 颜色键名
    public static final String PRIMARY_COLOR = "primaryColor";
    public static final String SECONDARY_COLOR = "secondaryColor";
    public static final String BACKGROUND_COLOR = "backgroundColor";
    public static final String PANEL_BACKGROUND_COLOR = "panelBackgroundColor";
    public static final String TEXT_COLOR = "textColor";
    public static final String SECONDARY_TEXT_COLOR = "secondaryTextColor";
    public static final String ACCENT_COLOR = "accentColor";
    public static final String BORDER_COLOR = "borderColor";
    public static final String HIGHLIGHT_COLOR = "highlightColor";
    public static final String SUCCESS_COLOR = "successColor";
    public static final String WARNING_COLOR = "warningColor";
    public static final String ERROR_COLOR = "errorColor";
    public static final String TABLE_HEADER_COLOR = "tableHeaderColor";
    public static final String TABLE_SELECTION_COLOR = "tableSelectionColor";
    public static final String SIDEBAR_BACKGROUND_COLOR = "sidebarBackgroundColor";
    public static final String ACTIVE_BUTTON_COLOR = "activeButtonColor";
    public static final String BUTTON_TEXT_COLOR = "buttonTextColor";
    public static final String SIDEBAR_TEXT_COLOR = "sidebarTextColor";
    public static final String SIDEBAR_ACTIVE_TEXT_COLOR = "sidebarActiveTextColor";

    static {
        // 初始化亮色主题颜色
        lightThemeColors.put(PRIMARY_COLOR, new Color(0, 130, 0));
        lightThemeColors.put(SECONDARY_COLOR, new Color(0, 160, 0));
        lightThemeColors.put(BACKGROUND_COLOR, new Color(245, 248, 250));
        lightThemeColors.put(PANEL_BACKGROUND_COLOR, Color.WHITE);
        lightThemeColors.put(TEXT_COLOR, new Color(60, 60, 60));
        lightThemeColors.put(SECONDARY_TEXT_COLOR, new Color(120, 120, 120));
        lightThemeColors.put(ACCENT_COLOR, new Color(0, 120, 0));
        lightThemeColors.put(BORDER_COLOR, new Color(230, 230, 230));
        lightThemeColors.put(HIGHLIGHT_COLOR, new Color(220, 240, 220));
        lightThemeColors.put(SUCCESS_COLOR, new Color(34, 139, 34));
        lightThemeColors.put(WARNING_COLOR, new Color(230, 150, 0));
        lightThemeColors.put(ERROR_COLOR, new Color(220, 0, 0));
        lightThemeColors.put(TABLE_HEADER_COLOR, new Color(245, 250, 245));
        lightThemeColors.put(TABLE_SELECTION_COLOR, new Color(220, 240, 220));
        lightThemeColors.put(SIDEBAR_BACKGROUND_COLOR, new Color(240, 245, 240));
        lightThemeColors.put(ACTIVE_BUTTON_COLOR, new Color(220, 240, 220));
        lightThemeColors.put(BUTTON_TEXT_COLOR, Color.WHITE);
        lightThemeColors.put(SIDEBAR_TEXT_COLOR, new Color(80, 80, 80));
        lightThemeColors.put(SIDEBAR_ACTIVE_TEXT_COLOR, new Color(0, 130, 0));

        // 初始化暗色主题颜色
        darkThemeColors.put(PRIMARY_COLOR, new Color(0, 150, 0));
        darkThemeColors.put(SECONDARY_COLOR, new Color(0, 180, 0));
        darkThemeColors.put(BACKGROUND_COLOR, new Color(45, 45, 45));
        darkThemeColors.put(PANEL_BACKGROUND_COLOR, new Color(60, 60, 60));
        darkThemeColors.put(TEXT_COLOR, new Color(230, 230, 230));
        darkThemeColors.put(SECONDARY_TEXT_COLOR, new Color(180, 180, 180));
        darkThemeColors.put(ACCENT_COLOR, new Color(0, 180, 0));
        darkThemeColors.put(BORDER_COLOR, new Color(80, 80, 80));
        darkThemeColors.put(HIGHLIGHT_COLOR, new Color(0, 100, 0));
        darkThemeColors.put(SUCCESS_COLOR, new Color(50, 180, 50));
        darkThemeColors.put(WARNING_COLOR, new Color(255, 180, 0));
        darkThemeColors.put(ERROR_COLOR, new Color(255, 70, 70));
        darkThemeColors.put(TABLE_HEADER_COLOR, new Color(70, 70, 70));
        darkThemeColors.put(TABLE_SELECTION_COLOR, new Color(0, 90, 0));
        darkThemeColors.put(SIDEBAR_BACKGROUND_COLOR, new Color(50, 50, 50));
        darkThemeColors.put(ACTIVE_BUTTON_COLOR, new Color(0, 100, 0));
        darkThemeColors.put(BUTTON_TEXT_COLOR, Color.WHITE);
        darkThemeColors.put(SIDEBAR_TEXT_COLOR, new Color(200, 200, 200));
        darkThemeColors.put(SIDEBAR_ACTIVE_TEXT_COLOR, new Color(120, 255, 120));
    }

    /**
     * 获取当前主题中的颜色
     * 
     * @param colorKey 颜色键名
     * @return 对应的颜色
     */
    public static Color getColor(String colorKey) {
        if (LIGHT_THEME.equals(currentTheme)) {
            return lightThemeColors.getOrDefault(colorKey, Color.BLACK);
        } else if (DARK_THEME.equals(currentTheme)) {
            return darkThemeColors.getOrDefault(colorKey, Color.WHITE);
        } else {
            // 系统主题，根据操作系统设置决定
            boolean isDarkMode = isDarkMode();
            return isDarkMode
                    ? darkThemeColors.getOrDefault(colorKey, Color.WHITE)
                    : lightThemeColors.getOrDefault(colorKey, Color.BLACK);
        }
    }

    /**
     * 设置当前主题
     * 
     * @param theme 主题名称
     */
    public static void setTheme(String theme) {
        if (theme == null || !theme.equals(currentTheme)) {
            currentTheme = theme;
            // 通知UI更新
            updateUI();
        }
    }

    /**
     * 获取当前主题
     * 
     * @return 当前主题名称
     */
    public static String getCurrentTheme() {
        return currentTheme;
    }

    /**
     * 更新UI
     */
    private static void updateUI() {
        SwingUtilities.invokeLater(() -> {
            // 更新Look and Feel
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

                // 更新UI管理器默认颜色
                updateUIManagerColors();

                // 更新所有窗口
                for (Window window : Window.getWindows()) {
                    SwingUtilities.updateComponentTreeUI(window);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 更新UI管理器默认颜色
     */
    private static void updateUIManagerColors() {
        UIManager.put("Panel.background", getColor(PANEL_BACKGROUND_COLOR));
        UIManager.put("Label.foreground", getColor(TEXT_COLOR));
        UIManager.put("Button.background", getColor(PRIMARY_COLOR));
        UIManager.put("Button.foreground", getColor(BUTTON_TEXT_COLOR));
        UIManager.put("TextField.background", DARK_THEME.equals(currentTheme) ? new Color(70, 70, 70) : Color.WHITE);
        UIManager.put("TextField.foreground", getColor(TEXT_COLOR));
        UIManager.put("TextArea.background", DARK_THEME.equals(currentTheme) ? new Color(70, 70, 70) : Color.WHITE);
        UIManager.put("TextArea.foreground", getColor(TEXT_COLOR));
        UIManager.put("ComboBox.background", DARK_THEME.equals(currentTheme) ? new Color(70, 70, 70) : Color.WHITE);
        UIManager.put("ComboBox.foreground", getColor(TEXT_COLOR));
        UIManager.put("Table.background", getColor(PANEL_BACKGROUND_COLOR));
        UIManager.put("Table.foreground", getColor(TEXT_COLOR));
        UIManager.put("Table.selectionBackground", getColor(TABLE_SELECTION_COLOR));
        UIManager.put("Table.selectionForeground", getColor(TEXT_COLOR));
        UIManager.put("TableHeader.background", getColor(TABLE_HEADER_COLOR));
        UIManager.put("TableHeader.foreground", getColor(TEXT_COLOR));
        UIManager.put("CheckBox.background", getColor(PANEL_BACKGROUND_COLOR));
        UIManager.put("CheckBox.foreground", getColor(TEXT_COLOR));
        UIManager.put("RadioButton.background", getColor(PANEL_BACKGROUND_COLOR));
        UIManager.put("RadioButton.foreground", getColor(TEXT_COLOR));
        UIManager.put("ScrollPane.background", getColor(PANEL_BACKGROUND_COLOR));
        UIManager.put("Viewport.background", getColor(PANEL_BACKGROUND_COLOR));
    }

    /**
     * 判断系统是否为暗色模式
     * 
     * @return 系统是否为暗色模式
     */
    private static boolean isDarkMode() {
        // 简单实现，根据系统属性判断
        String osName = System.getProperty("os.name").toLowerCase();
        if (osName.contains("mac")) {
            // MacOS
            try {
                // 尝试通过AppleScript检查暗色模式
                Process process = Runtime.getRuntime().exec(new String[] {
                        "osascript",
                        "-e",
                        "tell application \"System Events\" to tell appearance preferences to return dark mode"
                });
                String result = new java.util.Scanner(process.getInputStream()).useDelimiter("\\A").next().trim();
                return "true".equalsIgnoreCase(result);
            } catch (Exception e) {
                return false;
            }
        } else if (osName.contains("windows")) {
            // Windows 10+
            try {
                // 尝试通过注册表检查暗色模式
                Process process = Runtime.getRuntime().exec(
                        "reg query \"HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize\" /v AppsUseLightTheme");
                String result = new java.util.Scanner(process.getInputStream()).useDelimiter("\\A").next();
                return result.contains("0x0");
            } catch (Exception e) {
                return false;
            }
        }
        return false;
    }
}